"""
版类
"""
import requests
from lxml import etree
from end import End
from libs import getDomain
from thread import Thread

class Board(object):
    def __init__(self, url, background):
        response = requests.get(url)
        html = etree.HTML(response.text)
        self.threads = html.xpath('//*[@id="h-content"]//div[@class="h-threads-item-main"]')
        self.background = background
        self.url = response.url
        self.downPageUrl = html.xpath('//*[@id="h-content"]/div[1]/ul/li[last()-1]/a/@href')
        self.upPageUrl = html.xpath('//*[@id="h-content"]/div[1]/ul/li[1]/a/@href')

    def getAction(self, action):
        domain = getDomain(self.url)
        if action == 'up' or action == 'u':
            return Board(domain + self.upPageUrl[0], self) if len(self.upPageUrl)>0 else self
        elif action == 'down' or action == 'd':
            return Board(domain + self.downPageUrl[0], self) if len(self.downPageUrl)>0 else self
        elif action == 'menu':
            from menu import Menu
            return Menu()
        elif action == 'back' or action == 'b':
            return self.background
        elif action.isdigit() and int(action) < len(self.threads):
            threadUrl = domain + self.threads[int(action)].xpath('//a[@class="h-threads-info-id"]/@href')[0]
            return Thread(threadUrl, self)
        elif action == 'f':
            return Board(self.url, self.background)
        else:
            # TODO: 修改成使用WrongAction类
            print("无法识别")
            return self

    def show(self):
        if len(self.threads) == 0:
            print("无法解析！请按f重试或按q退出。")
            return True
        i = 0
        for thread in self.threads:
            title = thread.xpath('.//span[@class="h-threads-info-title"]/text()')[0]
            email = thread.xpath('.//span[@class="h-threads-info-email"]/text()')[0]
            createDate = thread.xpath('.//span[@class="h-threads-info-createdat"]/text()')[0]
            uid = thread.xpath('.//span[@class="h-threads-info-uid"]/text()')[0]
            url = thread.xpath('.//a[@class="h-threads-info-id"]/text()')[0]
            content = (''.join(thread.xpath('.//div[@class="h-threads-content"]//text()'))).strip()

            print(i, title, email, createDate, uid, url)
            print('---------------------------------------')
            print(content)
            print('=======================================')
            i += 1
        
        print('Up上一页/Down下一页/Back返回')
        return True

if __name__ == "__main__":
    board = Board('https://adnmb2.com/f/%E6%97%B6%E9%97%B4%E7%BA%BF', 'None')
    board.show()